<template>
  <div class="app-container">
    <div class="editor-container">
      <div class="editor-wrapper">
        <div class="editor-header">
          <span class="editor-title">代码编辑器</span>
          <div class="editor-actions">
            <!-- <el-select
              v-model="language"
              class="language-select"
              placeholder="选择语言"
            >
              <el-option
                v-for="lang in languages"
                :key="lang.value"
                :label="lang.label"
                :value="lang.value"
              />
            </el-select> -->
            <el-select
              v-model="theme"
              class="theme-select"
              placeholder="选择主题"
            >
              <el-option
                v-for="t in themes"
                :key="t.value"
                :label="t.label"
                :value="t.value"
              />
            </el-select>
            <el-button class="button-run" @click="runCode">运行代码</el-button>
            <!-- <el-button class="button-clear" @click="clearConsole"
              >清空输出</el-button
            > -->
          </div>
        </div>
        <div class="editor-content">
          <div ref="editorContainer" class="monaco-editor"></div>
        </div>
        <div class="status-bar">
          <span>行数: {{ lineCount }} | 长度: {{ codeLength }} 字符</span>
          <span>{{ language.toUpperCase() }} | {{ themeLabel }}</span>
        </div>
      </div>

      <!-- <div class="preview-container">
        

        <div class="preview-header">
          <span>控制台输出</span>
          <span>运行结果</span>
        </div>
        <div class="console-output">
          <div class="console-title">终端输出</div>
          <div>{{ consoleOutput }}</div>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, Ref, onMounted, watch, computed, onBeforeUnmount } from "vue";
import { ElSelect, ElOption, ElButton, ElMessage } from "element-plus";
import {
  gmtTaskDebug,
  gmtTaskinfosave,
  gmtTaskinfosaveParam,
} from "@/api/gmtTask";
import { gmtScriptDebugInfo } from "@/api/gmtScript";
import { useRoute } from "vue-router";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
const props = defineProps({
  modelValue: {
    type: String,
    default() {
      return "";
    },
  },
  taskForm: {
    type: Object,
    default() {
      return {};
    },
  },
  scriptValue: {
    type: Object,
    default() {
      return "";
    },
  },
});

// Emits 定义
const emit = defineEmits<{
  (e: "update:modelValue", value: any): void;
  (e: "runCode"): void;
}>();

const route = useRoute();

// 响应式数据
const code = ref();

const language = ref("javatask");
const theme = ref("vs-dark");
const consoleOutput = ref("");
const lineCount = ref(0);
const codeLength = ref(0);
const editorContainer = ref(null);
let editor = null;
// let monaco = null

const languages = ref([
  { value: "javatask", label: "Javatask" },
  { value: "typetask", label: "Typetask" },
  { value: "html", label: "HTML" },
  { value: "css", label: "CSS" },
  { value: "python", label: "Python" },
  { value: "java", label: "Java" },
  { value: "json", label: "JSON" },
]);

const themes = ref([
  { value: "vs", label: "浅色主题" },
  { value: "vs-dark", label: "深色主题" },
  { value: "hc-black", label: "高对比度" },
]);

// 计算属性
const themeLabel = computed(() => {
  const themeObj = themes.value.find((t) => t.value === theme.value);
  return themeObj ? themeObj.label : "";
});

const getgmtScriptDebugInfo = async () => {
  if (route.params.id != "add" || Object.keys(props.scriptValue).length != 0) {
    const data: any = gmtScriptDebugInfo(props.scriptValue.scriptId);
    // const scriptData: any = await gmtScriptinfo(route.params.scriptId);
    code.value = props.scriptValue.scriptContent;
    consoleOutput.value = await data.then((res) => {
      return res.excuteLog;
    });
    createEditor();
  }
};

// //获取代码详情
// const getGmtScriptinfo = () => {
//   code.value = gmtScriptinfo(route.params.scriptId);
// };
// getGmtScriptinfo();
// 创建编辑器实例
const createEditor = () => {
  if (!editorContainer.value) return;
  disposeEditor();
  // monaco = window.monaco
  editor = monaco.editor.create(editorContainer.value, {
    value: code.value,
    language: language.value,
    theme: theme.value,
    automaticLayout: true,
    minimap: { enabled: true },
    scrollBeyondLastLine: false,
    fontSize: 14,
    selectOnLineNumbers: true,
    roundedSelection: false,
    readOnly: true,
    cursorStyle: "line",
  });

  // 监听内容变化
  editor.onDidChangeModelContent(() => {
    const value = editor.getValue();
    code.value = value;
    updateLineCount();
  });

  updateLineCount();
};

function disposeEditor() {
  if (editor) {
    editor.dispose();
    const model = editor.getModel();
    if (model) {
      model.dispose();
    }
  }
}

const updateLineCount = () => {
  if (editor) {
    lineCount.value = editor.getModel().getLineCount();
    codeLength.value = code.value.length;
  }
};

const runCode = async () => {
  let taskId: any = route.params.id;
    await emit("runCode");
  if (route.params.id == "add") {
    await emit("runCode");
    // taskId = await gmtTaskinfosave({
    //   taskName: props.taskForm.taskName,
    //   taskDes: props.taskForm.taskDes,
    //   taskContent: props.taskForm.taskContent,
    // });
    // await gmtTaskinfosaveParam({
    //   taskId: taskId,
    //   taskParam: props.taskForm.taskParam,
    // });
  }
  // const data: any = await gmtTaskDebug(taskId);
  // consoleOutput.value = data.excuteLog || "代码已执行，但没有输出";
  // try {
  //   // 重写console.log捕获输出
  //   const originalConsole = console.log;
  //   let output = "";
  //   console.log = (...args) => {
  //     output += args.join(" ") + "\n";
  //   };

  //   // 执行代码
  //   if (language.value === "javatask") {
  //     // 使用eval执行代码
  //     eval(code.value);
  //   } else {
  //     output = `当前语言: ${language.value}，无法执行`;
  //   }

  //   // 恢复console.log
  //   console.log = originalConsole;

  //   // 显示输出
  //   consoleOutput.value = output || "代码已执行，但没有输出";

  //   // 显示成功消息
  //   ElMessage.success("代码执行成功");
  // } catch (error) {
  //   consoleOutput.value = `错误: ${error.message}`;
  //   ElMessage.error(`执行错误: ${error.message}`);
  // }
};

const clearConsole = () => {
  consoleOutput.value = "";
  ElMessage.info("控制台已清空");
};

// 监听语言变化
watch(language, (newLanguage) => {
  if (editor && monaco) {
    monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
    updateLineCount();
  }
});

// 监听主题变化
watch(theme, (newTheme) => {
  if (editor && monaco) {
    monaco.editor.setTheme(newTheme);
  }
});

watch(
  () => props.scriptValue,
  (newValue) => {
    getgmtScriptDebugInfo();
  }
);
// 监听代码变化更新行数
// watch(code, updateLineCount);

onMounted(() => {
  // getgmtScriptDebugInfo();
});

// 监听 props 变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (code.value !== newValue) {
      code.value = newValue;
      createEditor();
    }
  }
);

// 监听内容变化
watch(
  () => code.value,
  (newValue) => {
    emit("update:modelValue", newValue);
    updateLineCount();
  }
);

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose();
  }
});
</script>

<style scoped>
.app-container {
  /* max-width: 1200px; */
  width: 100%;
  /* display: flex; */
  margin: 0 auto;
}
.app-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 25px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  backdrop-filter: blur(4px);
}
.app-header h1 {
  font-size: 2.5rem;
  margin-bottom: 10px;
  background: linear-gradient(45deg, #1a2980, #26d0ce);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.app-header p {
  font-size: 1.2rem;
  color: #7f8c8d;
}
.editor-container {
  /* display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 25px; */
  margin-right: 30px;
  margin-bottom: 30px;
}
@media (max-width: 900px) {
  .editor-container {
    grid-template-columns: 1fr;
  }
}
.editor-wrapper,
.preview-container {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
  overflow: hidden;
  display: flex;
  /* width: 100%; */
  flex-direction: column;
}
.editor-header,
.preview-header {
  padding: 16px 20px;
  background: rgba(236, 240, 241, 0.8);
  border-bottom: 1px solid rgba(189, 195, 199, 0.5);
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.editor-title {
  font-weight: 600;
  color: #1a2980;
  font-size: 1.2rem;
}
.editor-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}
.editor-content {
  flex: 1;
  min-height: 400px;
}
.preview-content {
  padding: 20px;
  font-family: "Fira Code", "Courier New", monospace;
  white-space: pre-wrap;
  flex: 1;
  overflow: auto;
  background: #2d2d2d;
  color: #f8f8f2;
  line-height: 1.5;
}
.app-footer {
  text-align: center;
  color: #ecf0f1;
  font-size: 0.95rem;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  backdrop-filter: blur(5px);
}
.language-select,
.theme-select {
  width: 150px;
}
.button-run {
  background: linear-gradient(135deg, #00b09b, #96c93d);
  border: none;
  color: white;
  font-weight: 600;
  transition: all 0.3s;
}
.button-run:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(150, 201, 61, 0.4);
}
.button-clear {
  background: linear-gradient(135deg, #ff5e62, #ff9966);
  border: none;
  color: white;
  font-weight: 600;
  transition: all 0.3s;
}
.button-clear:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 94, 98, 0.4);
}
.console-output {
  background: #1e1e1e;
  color: #f8f8f2;
  padding: 15px;
  border-radius: 6px;
  margin: 15px;
  font-family: "Fira Code", "Courier New", monospace;
  /* max-height: 200px; */
  overflow: auto;
}
.console-title {
  color: #00b09b;
  margin-bottom: 8px;
  font-size: 0.9rem;
  display: flex;
  align-items: center;
  gap: 8px;
}
.console-title::before {
  content: "➜";
  color: #96c93d;
}
.status-bar {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background: rgba(236, 240, 241, 0.8);
  border-top: 1px solid rgba(189, 195, 199, 0.5);
  color: #7f8c8d;
  font-size: 0.85rem;
}
.monaco-editor {
  height: 400px;
  width: 100%;
}
.logo {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}
.logo-icon {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #1a2980, #26d0ce);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  font-weight: bold;
}
.feature-list {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  margin-top: 20px;
}
.feature {
  background: rgba(236, 240, 241, 0.6);
  padding: 12px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}
.feature-icon {
  color: #1a2980;
  font-weight: bold;
}
@media (max-width: 600px) {
  .feature-list {
    grid-template-columns: 1fr;
  }
  .editor-actions {
    justify-content: center;
  }
}
</style>
